import { Component, OnInit } from '@angular/core';
import { CATALOGUES } from '../book-catalogue-component/model/catalogues';
import { CatalogueSearchService } from './service/catalogue-search';
import { Catalogue } from '../book-catalogue-component/model/catalogues-model';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs';

@Component({
    selector: 'catalogue-search',
    templateUrl: 'catalogue-search.component.html',
    styleUrls: ['catalogue-search.scss']
})
export class CatalogueSearchComponent implements OnInit {
    catalogues: Observable<Catalogue[]>;
    // catalogues:Catalogue[];
    notFound = [new Catalogue()];
    private searchTerms = new Subject<string>();

    constructor(private catalogueSearch: CatalogueSearchService) { }

    ngOnInit() {
        this.catalogues = this.searchTerms
            .debounceTime(300)        // wait for 300ms pause in events
            .distinctUntilChanged()   // ignore if next search term is same as previous
            .map(term => term   // switch to new observable each time
                // return the http search observable
                ? this.catalogueSearch.search(term) : this.notFound)
            // or the observable of empty heroes if no search term
            // : Observable.of<Catalogue[]>([]));
            .catch(error => {
                // TODO: real error handling
                console.log(error);
                return Observable.of<Catalogue[]>(this.notFound);
            });
    }
    search(term: string): void {
        this.searchTerms.next(term.trim());
        // this.searchTerms.next(term);
        // this.catalogues = Observable.of<Catalogue[]>(this.catalogueSearch.search(term));
        // this.searchTerms.next(term);
        // this.catalogues = this.searchTerms
        //     .debounceTime(2000)        // wait for 300ms pause in events
        //     .distinctUntilChanged()   // ignore if next search term is same as previous
        //     .switchMap(term => term   // switch to new observable each time
        //         // return the http search observable
        //         ? this.catalogueSearch.search(term)
        //         // or the observable of empty heroes if no search term
        //         : Observable.of<Catalogue[]>([]))
        //     .catch(error => {
        //         // TODO: real error handling
        //         console.log(error);
        //         return Observable.of<Catalogue[]>([]);
        //     });

    }

}